import seedAgent from '@/services/seedAgent-service';
import { Button, Form, Input, message } from 'antd';
import React, { useState } from 'react';

const { TextArea } = Input;

interface DataRuleFormProps {
  agent_id: string;
  initialValues?: any;
  onSuccess?: () => void;
}

const DataRuleForm: React.FC<DataRuleFormProps> = ({
  agent_id,
  initialValues,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const payload = {
        ...values,
        agent_id,
      };

      if (initialValues) {
        await seedAgent.data_rules_update({
          rule_id: initialValues.rule_id,
          ...payload,
        });
        message.success('数据规则更新成功');
      } else {
        await seedAgent.data_rules_create(payload);
        message.success('数据规则创建成功');
      }

      if (onSuccess) onSuccess();
    } catch (error) {
      message.error('操作失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      initialValues={initialValues}
    >
      <Form.Item
        name="available_data"
        label="可用数据"
        rules={[{ required: true, message: '请输入可用数据' }]}
      >
        <Input placeholder="请输入可用数据" />
      </Form.Item>

      <Form.Item name="description" label="描述">
        <TextArea rows={4} placeholder="请输入描述信息" />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading}>
          {initialValues ? '更新' : '创建'}
        </Button>
      </Form.Item>
    </Form>
  );
};

export default DataRuleForm;
